<template>
  <div class="home-view">
    <Header />
    <div class="main-content">
      <div class="search-section">
        <SearchBar @search="handleSearch" />
      </div>
      
      <div class="products-section">
        <h2>热门商品</h2>
        
        <!-- 加载状态 -->
        <div v-if="loading" class="loading-container">
          <el-empty description="加载中..." />
        </div>
        
        <!-- 错误状态 -->
        <div v-else-if="error" class="error-container">
          <el-empty :description="error" />
          <el-button @click="fetchProducts" style="margin-top: 20px;">重试</el-button>
        </div>
        
        <!-- 商品列表 -->
        <div v-else class="products-grid">
          <ProductCard 
            v-for="product in filteredProducts" 
            :key="product.id" 
            :product="product" 
            @click="goToProductDetail(product.id)"
          />
        </div>
        
        <!-- 空状态 -->
        <div v-if="!loading && !error && filteredProducts.length === 0" class="empty-container">
          <el-empty description="暂无商品数据" />
        </div>
      </div>
    </div>
    <Footer />
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import Header from '@/components/Header.vue'
import Footer from '@/components/Footer.vue'
import SearchBar from '@/components/SearchBar.vue'
import ProductCard from '@/components/ProductCard.vue'
import { getProducts } from '@/api/product.js'

const router = useRouter()
const searchQuery = ref('')
const products = ref([])
const loading = ref(false)
const error = ref('')

// 从后端获取商品列表
const fetchProducts = async () => {
  loading.value = true
  error.value = ''
  try {
    const response = await getProducts({
      page: 1,
      pageSize: 20
    })
    
    // 处理后端返回的标准格式响应
    if (response && response.code === 200) {
      const productList = response.data.list || []
      // 处理商品数据，从images数组中提取第一张图片并赋值给image属性
      products.value = productList.map(product => ({
        ...product,
        image: product.images && product.images.length > 0 
          ? product.images[0].image || product.images[0] 
          : ''
      }))
    } else if (Array.isArray(response)) {
      // 兼容旧格式
      products.value = response
    } else {
      products.value = []
    }
  } catch (err) {
    error.value = '网络错误，请稍后重试'
    console.error('Fetch products error:', err)
  } finally {
    loading.value = false
  }
}

// 过滤商品
const filteredProducts = computed(() => {
  if (!searchQuery.value) return products.value
  return products.value.filter(product => 
    product.title?.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
    product.description?.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
    product.category?.toLowerCase().includes(searchQuery.value.toLowerCase())
  )
})

// 组件挂载时获取商品列表
onMounted(() => {
  fetchProducts()
})

const handleSearch = (query) => {
  if (query === '全部') {
    searchQuery.value = ''
  } else {
    searchQuery.value = query
  }
}

const goToProductDetail = (productId) => {
  router.push(`/product/${productId}`)
}
</script>

<style scoped>
.home-view {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

.main-content {
  flex: 1;
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
  width: 100%;
}

.search-section {
  margin-bottom: 30px;
}

.products-section h2 {
  margin-bottom: 20px;
  color: #333;
  font-size: 24px;
}

.products-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
}
</style>